package com.sun.showcase.biz.basic.service.impl;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sun.showcase.biz.basic.service.FtpClientService;
import com.sun.showcase.biz.basic.utils.FtpClientConstants;
import com.sun.showcase.client.domain.basic.UploadFile;
@Service
public class FtpClientServiceImpl implements FtpClientService {
	
//	private static final Logger LOGGER = LoggerFactory.getLogger( FtpClientServiceImpl.class );
	@Autowired
	private FtpClientConstants ftpClientConstants;//常量
	
	private ThreadLocal<FTPClient> ftpClientThreadLocal = new ThreadLocal<FTPClient>(); 
	
	public void setFtpClientConstants(FtpClientConstants ftpClientConstants) {
		this.ftpClientConstants = ftpClientConstants;
	}

	//链接ftp服务器
	private void openConnect() throws SocketException, IOException{
			
			int reply ;//重复请求链次数
			
			if(ftpClientThreadLocal.get()!=null&&ftpClientThreadLocal.get().isConnected())  
				return;
			
			
			FTPClient  ftpClient =	new FTPClient();//初始化
			
			ftpClient.connect(ftpClientConstants.getHost());//ip
			ftpClient.setDefaultPort(Integer.parseInt(ftpClientConstants.getPort()));//端口
			ftpClient.setControlEncoding("UTF-8");//编码
			
			reply = ftpClient.getReplyCode();
			
			//ftp 服务拒绝链接
			if(!FTPReply.isPositiveCompletion(reply)) 
				ftpClient.disconnect();
			
			//登陆用户
			if(!ftpClient.login(ftpClientConstants.getUsername(), 
					ftpClientConstants.getPassword()))
				disConnect();
			
			ftpClient.setDataTimeout(60000);       //设置传输超时时间为60秒 
		/*	ftpClient.setConnectTimeout(60000);       //连接超时为60秒
			ftpClient.setDefaultTimeout(60000);*/
			
			ftpClient.enterLocalPassiveMode(); 
			
			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
			
			ftpClient.setBufferSize(1024 * 1024 * 10);
			
			ftpClientThreadLocal.set(ftpClient);
	}
	
	//关闭链接
	private void disConnect(){
		
		FTPClient  ftpClient = ftpClientThreadLocal.get();
		
		if(ftpClient!=null){
			
			try {
				
				ftpClient.logout();
				
			} catch (Exception e) {
				
				e.printStackTrace();
				
			}finally{
				
				if(ftpClient.isConnected()){
					
					try {
						
						ftpClient.disconnect();
						
					} catch (IOException e) {
						
						e.printStackTrace();
						
					}
				}
			}
			
		}
	}
	
	@Override
	public InputStream findAttach(UploadFile uploadFile) {
		
		InputStream input = null;
		
		BufferedOutputStream output = null;
		
		try {
			//打开链接
			openConnect();
			FTPClient  ftpClient = ftpClientThreadLocal.get();
			
			File localFile= new File(ftpClientConstants.getDisk(),uploadFile.getSaveFileName());
			
			if(!localFile.exists()){
				
				output =new BufferedOutputStream(new FileOutputStream(localFile));

				if(StringUtils.isNotBlank(uploadFile.getFilePath())){
					
					ftpClient.changeWorkingDirectory(uploadFile.getFilePath());
				}

				ftpClient.retrieveFile(uploadFile.getSaveFileName(), output);
				
				if(output!=null){
					
					output.flush();
					
					output.close();
				}
			
			}
			
			input = new FileInputStream(localFile);
			
			/*input = ftpClient.retrieveFileStream(remoteFile);
			
			if(input!=null)
	        	input.close();//关闭流
		
	      if(!ftpClient.completePendingCommand())
	        	disConnect();*/

		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			
			disConnect();
		}

		return input;
	}
	
	public void findByFile(UploadFile uploadFile,OutputStream output){

		try {
			//打开链接
			openConnect();
			
			FTPClient  ftpClient = ftpClientThreadLocal.get();

			if(StringUtils.isNotBlank(uploadFile.getFilePath())){
				
				ftpClient.changeWorkingDirectory(uploadFile.getFilePath());
			}
			
			ftpClient.retrieveFile(uploadFile.getSaveFileName(), output);

		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			
			disConnect();
		}

	}

	public boolean saveFile(File file,UploadFile uploadFile) {
		
		
		boolean flag = true;
		
		try {
			//打开链接
			openConnect();

			FTPClient  ftpClient = ftpClientThreadLocal.get();

			ftpClient.changeWorkingDirectory(uploadFile.getFilePath());
			
	        BufferedInputStream  fiStream =new BufferedInputStream(new FileInputStream(file));

	        flag = ftpClient.storeFile(uploadFile.getSaveFileName(), fiStream);
	       
	        
	        fiStream.close();
		}catch(Exception e){
			
			e.printStackTrace();
			
		}finally{
			
			disConnect();
			
		}
		
		return flag;
		
	}
	public boolean saveFile(File file,String filePath,String fileName) {
		
		
		boolean flag = true;
		
		try {
			//打开链接
			openConnect();

			FTPClient  ftpClient = ftpClientThreadLocal.get();

			ftpClient.changeWorkingDirectory(filePath);
			
	        BufferedInputStream  fiStream =new BufferedInputStream(new FileInputStream(file));

	        flag = ftpClient.storeFile(fileName, fiStream);
	       
	        
	        fiStream.close();
		}catch(Exception e){
			
			e.printStackTrace();
			
		}finally{
			
			disConnect();
			
		}
		
		return flag;
		
	}
	public boolean saveFileAsStream(BufferedInputStream fiStream,String filePath,String fileName) {
		
		
		boolean flag = true;
		
		try {
			//打开链接
			openConnect();
			
			FTPClient  ftpClient = ftpClientThreadLocal.get();
			
			ftpClient.changeWorkingDirectory(filePath);
			
			//BufferedInputStream  fiStream =new BufferedInputStream(new FileInputStream(file));
			
			flag = ftpClient.storeFile(fileName, fiStream);
			
			
			fiStream.close();
		}catch(Exception e){
			
			e.printStackTrace();
			
		}finally{
			
			disConnect();
			
		}
		
		return flag;
		
	}
	/**
	 * 以文件流上传
	 * @param fiStream
	 * @param saveFileName
	 * @return
	 */
	public boolean saveFileAsStream(BufferedInputStream fiStream,UploadFile upload){
		boolean flag = true;
		
		try {
			//打开链接
			openConnect();
			FTPClient  ftpClient = ftpClientThreadLocal.get();

			ftpClient.changeWorkingDirectory(upload.getFilePath());
			
	        flag = ftpClient.storeFile(upload.getSaveFileName(), fiStream);
	       
	        
	        fiStream.close();
	        
		}catch(Exception e){
			
			e.printStackTrace();
			
		}finally{
			
			disConnect();
			
		}
		
		return flag;
		
	}
	
	public boolean deleteFile(UploadFile uploadFile) {		
		boolean flag = true;
		
		try {
			//打开链接
			openConnect();

			FTPClient  ftpClient = ftpClientThreadLocal.get();
			
			ftpClient.changeWorkingDirectory(uploadFile.getFilePath());
			
			flag = ftpClient.deleteFile(uploadFile.getSaveFileName()); 

		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}finally{
			disConnect();
		}
		return flag;
	}

	@Override
	public boolean generateDir() {
		
		boolean flag = true;
		
		try {
			//打开链接
			openConnect();

			FTPClient  ftpClient = ftpClientThreadLocal.get();
			
			//随机生成100个图片
			String root = "/goods";
			
			for(int i=0;i<100;i++){
				ftpClient.makeDirectory(root+i);//创建文件夹
				System.out.println("+++++++++++"+root+i);
			}
			
		} catch (Exception e) {
			flag = false;
			e.printStackTrace();
		}finally{
			disConnect();
		}
		return flag;
	}
	public static void main(String[] args) throws SocketException, IOException {
		FTPClient  ftpClient =	new FTPClient();//初始化
		
		ftpClient.connect("192.168.1.60");//ip
		ftpClient.setDefaultPort(21);//端口
		ftpClient.setControlEncoding("UTF-8");//编码
		//随机生成100个图片
		//ftp 服务拒绝链接
		/*if(!FTPReply.isPositiveCompletion(reply)) 
			ftpClient.disconnect();
		
		//登陆用户
		if(!ftpClient.login("root", 
				"123"))
			disConnect();*/
		ftpClient.login("root", 
				"123");
		ftpClient.setDataTimeout(60000);       //设置传输超时时间为60秒 
	/*	ftpClient.setConnectTimeout(60000);       //连接超时为60秒
		ftpClient.setDefaultTimeout(60000);*/
		
		ftpClient.enterLocalPassiveMode(); 
		
		ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
		
		ftpClient.setBufferSize(1024 * 1024 * 10);
		for(int i=500;i<600;i++){
			ftpClient.changeWorkingDirectory("root/datas/");
			ftpClient.makeDirectory("datas/datas"+StringUtils.leftPad(i+1+"", 3, "0")+"/");//创建文件夹
			System.out.println("goods"+StringUtils.leftPad(i+"", 3, "0")+"/");
		}
	}
}
